//
//  AuthenticateCommunityViewController.m
//  QRMaster
//
//  Created by myApple on 16/4/11.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "AuthenticateCommunityViewController.h"
#import "AuthenicateCommunityCell.h"
#import "AuthenicateCommuntiyModel.h"
#import "AuthenicateImageViewController.h"
#import "AuthenictateInfoViewController.h"
#import "RequestNetWork.h"
#import "MJExtension.h"
#import "AuthenBaseInfoModel.h"
#import "AutoLayoutFrame.h"
#import "MJRefresh.h"

@interface AuthenticateCommunityViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
{
    UITableView * communityInfoTableView;
    UIButton * authenicateBtn;
    BOOL btnCanSubmit;
    AuthenicateCommuntiyModel * authenModel;
    NSArray * textArray;//类型，物业信息等
    NSArray * imageArray;// text对应的图片
   __block NSMutableArray * contentArray;
   __block AuthenBaseInfoModel * model;
//    BOOL isFirst;
}

@end

@implementation AuthenticateCommunityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    authenModel = [[AuthenicateCommuntiyModel alloc]init];
    self.title = NSLocalizedString(@"communityInfo", @"物业信息");
    contentArray = [[NSMutableArray alloc]initWithArray:@[@"",@"",@"",@""]];
    self.view.backgroundColor = RGBA(237, 238, 240, 1);
    textArray = @[NSLocalizedString(@"communityStyle", @"类型"),NSLocalizedString(@"authenInfo", @"基本信息"),NSLocalizedString(@"authenImage", @"证件信息"),NSLocalizedString(@"authenStatus", @"认证状态")];
    [self prepareView];
    [self prepareData];
    
}

-(void)viewWillAppear:(BOOL)animated{
    if (btnCanSubmit) {
        [self enableBtn];
    }else{
        [self disableBtn];
    }
    [communityInfoTableView reloadData];
}

-(void)viewDidAppear:(BOOL)animated
{
//    [super viewDidAppear:animated];
//    if (authenModel.isInfoComplete && authenModel.hasImage) {
//        [self enableBtn];
//    }
//    if (btnCanSubmit) {
//        [self enableBtn];
//    }else{
//        [self disableBtn];
//    }
//    [communityInfoTableView reloadData];
//    //是否第一次进入
//    if (isFirst) {
//        authenicateBtn.enabled = NO;
//        isFirst = NO;
//    }
}


-(void)prepareView
{
    float x = 0 ;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = UI_SCREEN_HEIGHT - y;
    
    communityInfoTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    communityInfoTableView.delegate = self;
    communityInfoTableView.dataSource = self;
    communityInfoTableView.tableFooterView = [[UIView alloc]init];
    communityInfoTableView.backgroundColor = RGBA(237, 238, 240, 1);
    [self.view addSubview:communityInfoTableView];
    [communityInfoTableView.mj_header beginRefreshing];
    communityInfoTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self prepareData];
    }];

    
//    authenicateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
////    authenicateBtn.frame = CGRectMake(UI_SCREEN_WIDTH / 2.0 - 114, UI_SCREEN_HEIGHT - 108 - 64, 228, 48);
//    authenicateBtn.frame = [AutoLayoutFrame autoRect:CGRectMake(16, 56 * 4 + 110, UI_SCREEN_WIDTH - 32, 48)];
//    [authenicateBtn setTitle:NSLocalizedString(@"submitAuthen", @"提交认证") forState:0];
//    [authenicateBtn setBackgroundColor:UIColorFromRGBAndA(0x7dc234, 1)];
//    authenicateBtn.titleLabel.font = [UIFont systemFontOfSize:17.0];
//    [authenicateBtn setBackgroundColor:RGBA(0.0, 0.0, 0.0, 0.37)];
//    [authenicateBtn addTarget:self action:@selector(authenicateClick) forControlEvents:UIControlEventTouchUpInside];
//    authenicateBtn.layer.cornerRadius = 5;
//    authenicateBtn.layer.masksToBounds = YES;
//    authenicateBtn.enabled = NO;
//    [self.view addSubview:authenicateBtn];
}

-(void)enableBtn
{
    [authenicateBtn setBackgroundColor:UIColorFromRGBAndA(0x7dc234, 1)];
    authenicateBtn.enabled = YES;
}

-(void)disableBtn
{
    [authenicateBtn setBackgroundColor:UIColorFromRGBAndA(0x000000, 0.37)];
    authenicateBtn.enabled = NO;
}

-(void)authenicateClick
{
    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"feedBackAlterPromt", @"提示") message:NSLocalizedString(@"modifyAuthenPromt", @"改物业认证资料将重新审核，审核期间锁掌柜不可用")  delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel",@"取消") otherButtonTitles:NSLocalizedString(@"alterSure",@"确认"), nil];
    [alertView show];
   
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self authenCommunityInfo];
    }
}


#pragma mark ------------- UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 4;
    }
    else
    {
        return 0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * cellId = @"cell";
    AuthenicateCommunityCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[AuthenicateCommunityCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    cell.titleName = textArray[indexPath.row];
    cell.contentString = contentArray[indexPath.row];
    cell.hasInstruct = NO;
    if (indexPath.row == 1 || indexPath.row == 2) {
        cell.hasInstruct = YES;
    }
    if (indexPath.row == 3) {
        if (model.status == 2 || model.status == 3) {
            cell.authenColor = UIColorFromRGB(0x00aff0);
            cell.isShowImage = YES;
        }
        else
        {
            cell.authenColor = RGBA(255.0, 0.0, 0.0, 0.8);
            cell.isShowImage = NO;
        }
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 16.0;
    }
    else
    {
        return 80.0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if(section == 1)
    {
        return 160.0;
    }
    return 1.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        UIView * footView = [[UIView alloc]init];
        authenicateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        authenicateBtn.frame = [AutoLayoutFrame autoRect:CGRectMake(16, 30, UI_SCREEN_WIDTH - 32, 48)];
        [authenicateBtn setTitle:NSLocalizedString(@"submitAuthen", @"提交认证") forState:0];
        authenicateBtn.titleLabel.font = [UIFont systemFontOfSize:17.0];
        [authenicateBtn addTarget:self action:@selector(authenicateClick) forControlEvents:UIControlEventTouchUpInside];
        authenicateBtn.layer.cornerRadius = 5;
        authenicateBtn.layer.masksToBounds = YES;
//        if (authenModel.isInfoComplete && authenModel.hasImage) {
//            [self enableBtn];
//        }
//        else
//        {
//            [self disableBtn];
//        }
        if (btnCanSubmit) {
            [self enableBtn];
        }else{
            [self disableBtn];
        }

        [footView addSubview:authenicateBtn];
        
        return footView;
    }
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * headView = [[UIView alloc]init];
    headView.backgroundColor = RGBA(237, 238, 240, 1);
    if (section == 0) {
        headView.frame = CGRectMake(0, 0, UI_SCREEN_WIDTH, 16);
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 15.5, UI_SCREEN_WIDTH, 0.5)];
        lineView.backgroundColor = RGBA(193, 193, 193, 1);
        [headView addSubview:lineView];
    }
    else
    {
        headView.frame = CGRectMake(0, 0, UI_SCREEN_WIDTH, 80);
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 0.5)];
        lineView.backgroundColor = RGBA(193, 193, 193, 1);
        [headView addSubview:lineView];
    }
    return headView;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 1) {
        AuthenictateInfoViewController * infoVC = [[AuthenictateInfoViewController alloc]init];
        infoVC.infoModel = model;
        infoVC.info = ^(AuthenBaseInfoModel * infoModel)
        {
            authenModel.isInfoComplete = YES;
            model = infoModel;
            model.status = 0;
            [contentArray replaceObjectAtIndex:1 withObject:@""];
            [self checkStatus:0];
            if (authenModel.isInfoComplete && authenModel.hasImage) {
//                [self enableBtn];
                btnCanSubmit = YES;
                [communityInfoTableView reloadData];
            }
            if (self.status) {
                self.status(model.status);
            }
        };
        [self.navigationController pushViewController:infoVC animated:YES];
    }
    else if(indexPath.row == 2)
    {
        AuthenicateImageViewController * imageVC = [[AuthenicateImageViewController alloc]init];
        imageVC.infoModel = model;
        imageVC.hasImage = ^(AuthenBaseInfoModel * imageModel)
        {
            authenModel.hasImage = YES;
            [contentArray replaceObjectAtIndex:2 withObject:@""];
            model = imageModel;
            model.status = 0;
            [self checkStatus:0];
            if (authenModel.isInfoComplete && authenModel.hasImage) {
//                [self enableBtn];
                btnCanSubmit = YES;
//                [communityInfoTableView reloadData];
            }
            if (self.status) {
                self.status(model.status);
            }
        };
        [self.navigationController pushViewController:imageVC animated:YES];
    }
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -------- 获取集群认证信息
-(void)prepareData
{
    if ([self IsHaveNetwork]) {
        return;
    }
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    [postDict setValue:UID forKey:@"id"];
    [postDict setValue:TOKEN forKey:@"token"];
    [self startWaiting:nil color:nil addToView:self.view];
    __weak AuthenticateCommunityViewController * weakSelf = self;
    [rnk initWithPath:POST(GETAUTHINFO) params:postDict block:^(id downLoadData, id error) {
        [weakSelf stopWaiting];
        DDLOG(@"认证==%@",downLoadData);
        if ([downLoadData objectForKey:@"data"] != nil) {
            [contentArray replaceObjectAtIndex:0 withObject:_communityStyle];
            NSDictionary * dict = [downLoadData objectForKey:@"data"];
            if ([dict[@"canSubmit"] intValue]) {
                btnCanSubmit = YES;
//                [self enableBtn];
            }else{
                btnCanSubmit = NO;
//                [self disableBtn];
            }
            model = [AuthenBaseInfoModel mj_objectWithKeyValues:dict];
            if (model.authType == 1) {
                if ([model.name isEqualToString:@""]|| [model.address isEqualToString:@""]|| [model.corporation isEqualToString:@""] || [model.mobile isEqualToString:@""]) {
                    [contentArray replaceObjectAtIndex:1 withObject:NSLocalizedString(@"notComplete", @"信息不完整") ];
                    authenModel.isInfoComplete = NO;
                }
                else
                {
                    [contentArray replaceObjectAtIndex:1 withObject:@""];
                    authenModel.isInfoComplete = YES;
                }
                if ([model.no isEqualToString:@""] || [model.image isEqualToString:@""]) {
                    [contentArray replaceObjectAtIndex:2 withObject:NSLocalizedString(@"notComplete", @"未上传")];
                    authenModel.hasImage = NO;
                }
                else
                {
                    [contentArray replaceObjectAtIndex:2 withObject:@""];
                    authenModel.hasImage = YES;
                }
            }
            else if (model.authType == 2)
            {
                if ([model.name isEqualToString:@""]) {
                    [contentArray replaceObjectAtIndex:1 withObject:NSLocalizedString(@"notComplete", @"信息不完整") ];
                    authenModel.isInfoComplete = NO;
                }
                else
                {
                    [contentArray replaceObjectAtIndex:1 withObject:@""];
                    authenModel.isInfoComplete = YES;
                }
                if ([model.no isEqualToString:@""]||[model.image isEqualToString:@""]) {
                    [contentArray replaceObjectAtIndex:2 withObject:NSLocalizedString(@"notComplete", @"未上传")];
                    authenModel.hasImage = NO;
                }
                else
                {
                    [contentArray replaceObjectAtIndex:2 withObject:@""];
                    authenModel.hasImage = YES;
                }
            }
            if (authenModel.isInfoComplete && authenModel.hasImage) {
                [self enableBtn];
            }
            if (weakSelf.status) {
                weakSelf.status(model.status);
            }
            [weakSelf checkStatus:model.status];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
            btnCanSubmit = YES;
            [communityInfoTableView reloadData];
        }
        [communityInfoTableView.mj_header endRefreshing];
    }];
    [communityInfoTableView reloadData];
}

#pragma mark ---------- 提交认证信息
-(void)authenCommunityInfo
{
    if ([self IsHaveNetwork]) {
        return;
    }
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    [postDict setValue:UID forKey:@"id"];
    [postDict setValue:TOKEN forKey:@"token"];
    [self startWaiting:nil color:nil addToView:self.view];
    __weak AuthenticateCommunityViewController * weakSelf = self;
    [rnk initWithPath:POST(SUBMITAUTHINFO) params:postDict block:^(id downLoadData, id error) {
        [weakSelf stopWaiting];
        DDLOG(@"downLoadData = %@",downLoadData);
        if ([downLoadData objectForKey:@"data"] != nil) {
            model.status = 1;
            [weakSelf checkStatus:model.status];
            [weakSelf disableBtn];
            [PromptInfoView showMessage:NSLocalizedString(@"sumbitAuthenSuccess", @"认证申请已提交")];
            if (weakSelf.status) {
                weakSelf.status(model.status);
            }
             [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
            [weakSelf enableBtn];
        }
    }];
}

-(void)checkStatus:(NSInteger)count
{
    switch (count) {
        case 0:
            [contentArray replaceObjectAtIndex:3 withObject:NSLocalizedString(@"notAuthen", @"未认证")];
            break;
        case 1:
            [contentArray replaceObjectAtIndex:3 withObject:NSLocalizedString(@"needVerify", @"认证中")];
            break;
        case 2:
            [contentArray replaceObjectAtIndex:3 withObject:NSLocalizedString(@"authenicate", @"已认证")];
            break;
        case 3:
            [contentArray replaceObjectAtIndex:3 withObject:NSLocalizedString(@"authenicate", @"已认证")];
            break;
        case 4:
            [contentArray replaceObjectAtIndex:3 withObject:NSLocalizedString(@"authenfalse", @"认证失败")];
            break;
        default:
            [contentArray replaceObjectAtIndex:3 withObject:NSLocalizedString(@"notAuthen", @"未认证")];
            break;
    }
    [communityInfoTableView reloadData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
